<?php
/*
 * 公共基类控制器
 */

namespace App\Http\Controllers\Web;

use App\ConstDir\ErrorConst;
use Laravel\Lumen\Routing\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\Auth;

class BaseController extends Controller
{

    protected $perPage = 15;

    protected $user = null;

    public function __construct()
    {
        static::formatErrorsUsing(function ($validator) {
            return [
                'code' => ErrorConst::FAILED_CODE,
                'message' => $validator->errors()->getMessages(),
                'data' => null,
            ];
        });

        $this->user =   Auth::check() ? Auth::user() :'';
    }


    /*
     * 错误提示
     */
    public function error($message, $code = ErrorConst::FAILED_CODE)
    {
        return collect([
                'code' => $code,
                'message' => $message,
                'data' => null,
            ]
        );
    }

    /*
     * 成功返回提示
     */
    public function success($message, $data = null, $page = null)
    {
        if($page && isset($data['meta'])){
            $ret = [
                'list' => $data['data'],
                'page' => $data['meta']['pagination']
            ];
        }else{
            $ret = $data;
        }
        return collect([
            'code' => ErrorConst::SUCCESS_CODE,
            'message' => $message,
            'data' => $ret
        ]);
    }

    /*
     * 无数据的返回
     */
    public function noDataReturn($status)
    {
        if ($status) {
            return $this->success(ErrorConst::SUCCESS_CODE_MSG);
        } else {
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
    }
}